package com.music.note_android.ui.folder

import android.app.Dialog
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import com.music.note_android.R
import com.music.note_android.data.model.Folder

class RenameFolderDialog : DialogFragment() {

    private lateinit var tvCurrentName: TextView
    private lateinit var tilFolderName: TextInputLayout
    private lateinit var etFolderName: TextInputEditText
    private lateinit var btnCancel: MaterialButton
    private lateinit var btnConfirm: MaterialButton
    
    private var folder: Folder? = null
    private var onFolderRenamed: ((String) -> Unit)? = null

    companion object {
        private const val ARG_FOLDER_ID = "folder_id"
        private const val ARG_FOLDER_NAME = "folder_name"
        
        fun newInstance(folder: Folder, onFolderRenamed: (String) -> Unit): RenameFolderDialog {
            return RenameFolderDialog().apply {
                arguments = Bundle().apply {
                    putString(ARG_FOLDER_ID, folder.id)
                    putString(ARG_FOLDER_NAME, folder.name)
                }
                this.folder = folder
                this.onFolderRenamed = onFolderRenamed
            }
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_rename_folder, null)
        
        initViews(view)
        setupListeners()
        loadFolderData()
        
        return AlertDialog.Builder(requireContext())
            .setView(view)
            .create()
    }

    private fun initViews(view: View) {
        tvCurrentName = view.findViewById(R.id.tv_current_name)
        tilFolderName = view.findViewById(R.id.til_folder_name)
        etFolderName = view.findViewById(R.id.et_folder_name)
        btnCancel = view.findViewById(R.id.btn_cancel)
        btnConfirm = view.findViewById(R.id.btn_confirm)
        
        // 初始状态下确认按钮不可用
        btnConfirm.isEnabled = false
    }

    private fun loadFolderData() {
        val folderName = arguments?.getString(ARG_FOLDER_NAME) ?: ""
        tvCurrentName.text = "当前名称：$folderName"
        etFolderName.setText(folderName)
        etFolderName.selectAll()
    }

    private fun setupListeners() {
        // 文本变化监听
        etFolderName.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                validateInput()
            }
            
            override fun afterTextChanged(s: Editable?) {}
        })
        
        // 取消按钮
        btnCancel.setOnClickListener {
            dismiss()
        }
        
        // 确认按钮
        btnConfirm.setOnClickListener {
            val newFolderName = etFolderName.text?.toString()?.trim()
            if (!newFolderName.isNullOrEmpty() && validateFolderName(newFolderName)) {
                onFolderRenamed?.invoke(newFolderName)
                dismiss()
            }
        }
    }

    private fun validateInput() {
        val newFolderName = etFolderName.text?.toString()?.trim()
        val originalName = arguments?.getString(ARG_FOLDER_NAME) ?: ""
        
        when {
            newFolderName.isNullOrEmpty() -> {
                tilFolderName.error = null
                btnConfirm.isEnabled = false
            }
            newFolderName == originalName -> {
                tilFolderName.error = "新名称与原名称相同"
                btnConfirm.isEnabled = false
            }
            !validateFolderName(newFolderName) -> {
                btnConfirm.isEnabled = false
            }
            else -> {
                tilFolderName.error = null
                btnConfirm.isEnabled = true
            }
        }
    }

    private fun validateFolderName(name: String): Boolean {
        return when {
            name.isEmpty() -> {
                tilFolderName.error = "文件夹名称不能为空"
                false
            }
            name.length > 50 -> {
                tilFolderName.error = "文件夹名称不能超过50个字符"
                false
            }
            name.contains("/") || name.contains("\\") -> {
                tilFolderName.error = "文件夹名称不能包含特殊字符"
                false
            }
            name.trim() != name -> {
                tilFolderName.error = "文件夹名称首尾不能有空格"
                false
            }
            else -> {
                tilFolderName.error = null
                true
            }
        }
    }

    override fun onStart() {
        super.onStart()
        // 显示软键盘并选中文本
        etFolderName.requestFocus()
        etFolderName.selectAll()
    }
}